<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <span class="tag">基础信息</span>
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="客户单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerOrderNo">
              <a-input v-model.trim="model.customerOrderNo" placeholder="请输入客户单号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="货物类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="goodsType">
              <j-dict-select-tag type="list" v-model="model.goodsType" dictCode="logistics_goods_type" placeholder="请选择货物类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="卖家税号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sellerTaxId">
              <a-input v-model.trim="model.sellerTaxId" placeholder="请输入卖家税号" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider/>
        <span class="tag">收件人信息</span>
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="收件人姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="recipientName">
              <a-input v-model.trim="model.recipientName" placeholder="请输入收件人姓名" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="收件人地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="recipientAddress">
              <a-input v-model.trim="model.recipientAddress" placeholder="请输入收件人地址" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="国家" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="countryCode">
              <j-search-select-tag v-model="model.countryCode" dict="hz_logistics_country_default,cn_name,code,logistics"  />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="省/州" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provincial">
              <a-input v-model.trim="model.provincial" placeholder="请输入省/州" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="城市" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="city">
              <a-input v-model.trim="model.city" placeholder="请输入城市" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="邮编" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="zipCode">
              <a-input v-model.trim="model.zipCode" placeholder="请输入邮编" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="电话号码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="mobilePhone">
              <a-input v-model.trim="model.mobilePhone" placeholder="请输入电话号码" ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="物流包裹信息" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="logisticsWaybillPackageTable.loading"
          :columns="logisticsWaybillPackageTable.columns"
          :dataSource="logisticsWaybillPackageTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          @deleted="handleDeleted"
          @valueChange="handleValueChange"
        />
      </a-tab-pane>
    </a-tabs>
    <a-divider/>
    <span class="tag">物流产品</span>
    <div class="table-content" id="table-content-container">
      <div class="table-text">
        <a-button type="primary" @click="getPriceComparisonList('')" :disabled="formDisabled">
          <img src="@/assets/fly.png">
          <span>物流产品</span>
        </a-button>
        <a-button type="primary" ghost>
          <img src="@/assets/care.png">
          <span>填写全部必填项后，点击物流产品，方可查看并选择可用物流产品</span>
        </a-button>
      </div>
      <a-tabs type="card" v-model="activeKey_">
        <a-tab-pane key="1" tab="物流比价模式">
          <logistics-waybill-detail-form-table v-model="checkedList" :dataSource="dataSource" :columns="columns" :formDisabled="formDisabled" />
        </a-tab-pane>
        <a-tab-pane key="2" tab="专线选择模式">
          <div class="special-line-container">
            <div class="special-line-left">
              <div class="table-page-search-wrapper">
                <a-form layout="inline" >
                  <a-row :gutter="24">
                    <a-col :md="12" :sm="12">
                      <a-form-item label="物流产品" :labelCol="labelCol" :wrapperCol="wrapperCol">
                        <j-dict-select-tag placeholder="请选择物流产品" :getPopupContainer = "getPopupContainer" v-model="queryParam.productId" dictCode="hz_logistics_product,name,id,logistics"/>
                      </a-form-item>
                    </a-col>
                    <a-col :md="6" :sm="8">
                      <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                        <a-button type="primary" @click="getPriceComparisonList('search')" icon="search">查询</a-button>
                        <a-button type="primary" @click="searchReset_" icon="reload" style="margin-left: 8px">重置</a-button>
                      </span>
                    </a-col>
                  </a-row>
                  <logistics-waybill-detail-form-table v-model="checkedList" :dataSource="dataSource_" :columns="columns_" :formDisabled="formDisabled" />
                </a-form>
              </div>
            </div>
            <div class="special-line-right">
              <logistics-waybill-detail-form-table v-model="checkedList" :dataSource="dataSource__" :columns="columns_" :formDisabled="formDisabled" />
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-spin>
</template>

<script>
  import { getAction, postAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import LogisticsWaybillDetailFormTable from './LogisticsWaybillDetailFormTable';
  export default {
    name: 'LogisticsWaybillDetailForm',
    mixins: [JEditableTableModelMixin, JeecgListMixin],
    components: { LogisticsWaybillDetailFormTable },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{},
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          customerOrderNo: [
            { required: true, message: '请输入客户单号!'},
          ],
          goodsType: [
            { required: true, message: '请输入货物类型!'},
          ],
          sellerTaxId: [
            { required: true, message: '请输入卖家税号!'},
          ],
          recipientName: [
            { required: true, message: '请输入收件人姓名!'},
          ],
          recipientAddress: [
            { required: true, message: '请输入收件人地址!'},
          ],
          countryCode: [
            { required: true, message: '请输入国家!'},
          ],
          provincial: [
            { required: true, message: '请输入省/州!'},
          ],
          city: [
            { required: true, message: '请输入城市!'},
          ],
          zipCode: [
            { required: true, message: '请输入邮编!'},
          ],
          mobilePhone: [
            { required: true, message: '请输入电话号码!'},
          ],
        },
        refKeys: ['logisticsWaybillPackage', ],
        tableKeys:['logisticsWaybillPackage', ],
        activeKey: 'logisticsWaybillPackage',
        // 物流包裹信息
        logisticsWaybillPackageTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '重量（kg）',
              key: 'weight',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '长度（cm）',
              key: 'length',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '宽度（cm）',
              key: 'width',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '高度（cm）',
              key: 'height',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '中文名称',
              key: 'cnName',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '英文名称',
              key: 'enName',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: 'SKU',
              key: 'sku',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '申报数量（个）',
              key: 'quantity',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '申报单价（$）',
              key: 'unitPrice',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '申报总价（$）',
              key: 'totalPrice',
              type: FormTypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '海关编码',
              key: 'customsCode',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '中文材质',
              key: 'cnMaterial',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '英文材质',
              key: 'enMaterial',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '备注',
              key: 'remark',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          add: "/logistics/waybill/logisticsWaybillDetail/add",
          edit: "/logistics/waybill/logisticsWaybillDetail/edit",
          queryById: "/logistics/waybill/logisticsWaybillDetail/queryById",
          logisticsWaybillPackage: {
            list: '/logistics/waybill/logisticsWaybillDetail/queryLogisticsWaybillPackageByMainId',
            priceComparisonList: '/logistics/waybill/logisticsWaybillDetail/priceComparisonList'
          },
        },
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'物流商',
            align:"center",
            dataIndex: 'providerName',
            scopedSlots: { customRender: 'providerNameSlot' }
          },
          {
            title:'物流产品名称',
            align:"center",
            dataIndex: 'productName',
            scopedSlots: { customRender: 'productNameSlot' }
          },
          {
            title:'计费分区',
            align:"center",
            dataIndex: 'classifyName',
            scopedSlots: { customRender: 'classifyNameSlot' }
          },
          {
            title:'计费重量',
            align:"center",
            dataIndex: 'chargeWeight'
          },
          {
            title:'计费模式',
            align:"center",
            dataIndex: 'calculateMethod'
          },
          {
            title:'运费估算',
            align:"center",
            dataIndex: 'shippingFee'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        disableMixinCreated: true,
        activeKey_: '1',
        dataSource_: [],
        dataSource__: [],
        checkedList: '',
        waybillStatus: '',
        getPopupContainer: () => document.getElementById('table-content-container')
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      columns_(){
        return this.columns.filter(item => item.dataIndex != 'chargeWeight' && item.dataIndex != 'calculateMethod' && item.dataIndex != 'shippingFee')
      }
    },
    watch: {
      'model.countryCode': {
        handler(){
          //国家改变重置物流产品列表
          this.resetTable();
        }
      },
      'model.zipCode': {
        handler(){
          //邮编改变重置物流产品列表
          this.resetTable();
        }
      }
    },
    created () {
      this.$nextTick(() => {
        // 物流包裹信息只保留一条信息
        let dom = document.querySelector('.ant-btn-group');
        dom && dom.addEventListener('click', () => {
          let ref = this.refKeys[0];
          let rows = this.$refs[ref].rows;
          if(rows && rows.length){
            dom.style.display = 'none';
          }
        })
      })
    },
    beforeDestroy(){
      let dom = document.querySelector('.ant-btn-group');
      dom && dom.removeEventListener('click');
    },
    methods: {
      addBefore(){
        this.logisticsWaybillPackageTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        // 加载子表数据
        if (this.model.id) {
          //回显数据
          if(this.model.waybillDetailId){
            this.getQueryById(this.model.waybillDetailId).then((res) => {
              //获取表单数据
              this.model = {...this.model, ...res};
              // 获取物流包裹信息
              this.requestSubTableData(this.url.logisticsWaybillPackage.list, { id: this.model.waybillDetailId }, this.logisticsWaybillPackageTable, (res_) => {
                // 物流包裹信息只保留一条信息
                if(res_ && res_.result && res_.result.length){
                  let dom = document.querySelector('.ant-btn-group');
                  if(dom){
                    dom.style.display = 'none';
                  }
                }
                // 表格数据渲染需要一定时间
                setTimeout(() => {
                  if(res_ && res_.result && res_.result[0]){
                    // 渲染物流产品信息
                    this.getPriceComparisonList();
                  }
                }, 100)
              })
            })
          }
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
        return new Promise((resolve,reject)=>{
          Promise.all([
          ]).then(() => {
            resolve(allValues)
          }).catch(e => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
        })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          logisticsWaybillPackageList: allValues.tablesValue[0].values,
          productId: this.checkedList,
          waybillStatus: this.waybillStatus
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      getPriceComparisonList(type){
        if(!this.model.countryCode){
          this.$message.warning('请选择国家');
          return;
        }
        if(!this.model.zipCode){
          this.$message.warning('请输入邮编');
          return;
        }
        let ref = this.refKeys[0];
        this.$refs[ref].getValues((error, values) => {
          if (error === 0) {
            if(!(values && values.length)){
              this.$message.warning('请填写包裹信息');
              return;
            }
            if(!type){
              this.handlePost(1, values);
            }
            this.handlePost(2, values);
            this.handlePost(3, values);
          } else {
            // this.$message.error('验证未通过')
          }
        })
      },
      handlePost(productModeType, values){
        let params = {
          productModeType,
          countryCode: this.model.countryCode,
          zipCode: this.model.zipCode,
          weight: values[0].weight,
          productId: this.queryParam.productId,
        }
        postAction(this.url.logisticsWaybillPackage.priceComparisonList, params).then((res) => {
          if(res.success){
            //回显逻辑
            if(this.model.productId){
              let checkedList = res.result.find(item => {
                return item.id === this.model.productId;
              });
              if(checkedList.id){
                this.checkedList = checkedList.id;
              }
            }
            if(productModeType === 1){
              this.dataSource = res.result || [];
            }else if(productModeType === 2){
              this.dataSource_ = res.result || [];
            }else if(productModeType === 3){
              this.dataSource__ = res.result || [];
            }
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handleDeleted(e, o){
        let dom = document.querySelector('.ant-btn-group');
        if(!(o.rows && o.rows.length) && dom){
          dom.style.display = 'block';
        }
      },
      handleOk_(waybillStatus){
        // 保存，不用校验必填项
        if(waybillStatus === '1'){
          let params = {
            ...this.model,
            logisticsWaybillPackageList: this.logisticsWaybillPackageTable.dataSource || [],
            productId: this.checkedList,
            waybillStatus
          }
          this.request(params);
          return;
        }
        if(!this.checkedList){
          this.$message.warning('请选择物流产品');
          return;
        }
        this.waybillStatus = waybillStatus ;
        this.handleOk();
      },
      searchReset_(){
        this.queryParam.productId = '';
        this.getPriceComparisonList('search');
      },
      handleClear(){
        this.$refs.form.resetFields();
        let ref = this.refKeys[0];
        this.$refs[ref].initialize();
        this.handleDeleted('', '');
        this.checkedList = '';
      },
      getQueryById( id ){
        return new Promise((resolve, reject) => {
          getAction(this.url.queryById, { id }).then((res) => {
            if(res.success){
              resolve(res.result);
            }else{
              this.$message.warning(res.message);
            }
          })
        })
      },
      resetTable(){
        this.dataSource = [];
        this.dataSource_ = [];
        this.dataSource__ = [];
      },
      handleValueChange(event){
        //重量变更
        if(event.column.key === 'weight'){
          this.resetTable();
        }
        //获取申报总价
        let ref = this.refKeys[0];
        this.$refs[ref].getValues((error, values) => {
          // 错误数 = 0 则代表验证通过
          if (error === 0) {
            this.logisticsWaybillPackageTable.dataSource = [{
              ...values[0],
              totalPrice: (((values[0].quantity * 100) * (values[0].unitPrice * 100)) / 10000).toFixed(2)
            }]
          } else {
            // this.$message.error('验证未通过')
          }
        })
      }
    }
  }
</script>

<style scoped lang="less">
.tag{
  border: 1px solid #1890FF;
  padding: 2px 10px;
  border-radius: 6px;
  color: #1890FF;
  margin-bottom: 4px;
  display: inline-block;
}
/deep/.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab-active{
  border-color: #1890FF;
  border-bottom: 1px solid #fff;
  background: rgba(24,144,255, 0.1);
}
/deep/.ant-tabs.ant-tabs-card .ant-tabs-card-bar .ant-tabs-tab{
  border-color: #1890FF;
  border-bottom: 1px solid #fff;
  color: #1890FF;
}
.table-content{
  position: relative;
  .table-text{
    position: absolute;
    left: 30%;
    z-index: 9;
    img{
      width: 16px;
      margin-right: 4px;
    }
    .ant-btn-background-ghost{
      margin-left: 8px;
    }
  }
}
.special-line-container{
  display: flex;
  .special-line-left{
    flex: 1;
    margin-top: 20px;
  }
  .special-line-right{
    flex: 1;
    margin-top: 76px;
    margin-left: 10px;
  }
}
</style>